<script setup>
	import { PlusOutlined } from '@ant-design/icons-vue'
	import XnUpload from '@/components/XnUpload/index.vue'

	const props = defineProps({
		// 单选答案
		issueOption: {
			type: String,
			required: true
		},
		answer: {
			type: String,
			required: true
		}
	})
	// 定义 emit
	const emit = defineEmits(['updateIssueOption', 'updateAnswer'])

	// 单选答案
	const issueOptionLocal = ref([
		{ key: 'A', value: 'a' },
		{ key: 'B', value: 'b' },
		{ key: 'C', value: 'c' }
	])
	const answerLocal = ref('A')
	watch(
		() => issueOptionLocal,
		(newVal) => {
			emit('updateIssueOption', JSON.stringify(newVal.value))
		},
		{ deep: true }
	)
	// 模拟 created 生命周期
	onBeforeMount(() => {
		try {
			const data = JSON.parse(props.issueOption)
			if (data && Array.isArray(data)) {
				issueOptionLocal.value = data
			}
			answerLocal.value = props.answer
		} catch (e) {
			/* empty */
		}
	})

	//新增单选
	const addIssueOption = () => {
		const newKey = String.fromCharCode('A'.charCodeAt(0) + issueOptionLocal.value.length)
		issueOptionLocal.value.push({ key: newKey, value: '' })
	}
	// 删除单选
	const removeIssueOption = (index) => {
		if (answerLocal.value === issueOptionLocal.value[index].key) {
			answerLocal.value = ''
			emit('updateAnswer', '')
		}
		issueOptionLocal.value.splice(index, 1)
		for (let i = 0; i < issueOptionLocal.value.length; i++) {
			if (i >= index) {
				const newKey = String.fromCharCode('A'.charCodeAt(0) + i)
				if (answerLocal.value === issueOptionLocal.value[i].key) {
					answerLocal.value = newKey
					emit('updateAnswer', newKey)
				}
				issueOptionLocal.value[i].key = newKey
			}
		}
	}
	//设置为答案
	const setAsAnswer = (key) => {
		answerLocal.value = key
		emit('updateAnswer', key)
	}
	//取消答案
	const setNotAnswer = () => {
		answerLocal.value = ''
		emit('updateAnswer', '')
	}
</script>

<template>
	<a-form-item v-for="(option, index) in issueOptionLocal" :key="index" :label="`选项 ${option.key}`">
		<a-row :gutter="16" justify="space-around" align="middle">
			<a-col :span="16">
				<a-input v-model:value="option.value" placeholder="请输入选项值" />
			</a-col>
			<a-col :span="8">
				<a-space>
					<a-button danger @click="removeIssueOption(index)">删除</a-button>
					<a-button type="primary" @click="setAsAnswer(option.key)" v-if="option.key !== answerLocal"
						>设为答案</a-button
					>
					<a-button type="link" @click="setNotAnswer()" v-else>取消答案</a-button>
					<xn-upload v-model:value="option.value" uploadText="上传图片" :showUploadList="false" />
				</a-space>
			</a-col>
		</a-row>
	</a-form-item>
	<a-form-item :wrapper-col="{ offset: 4, span: 20 }">
		<a-button type="dashed" block @click="addIssueOption">
			<PlusOutlined />
			添加选项
		</a-button>
	</a-form-item>
</template>

<style scoped lang="less"></style>
